package com.siteseat.crudeq.common.raw.protocol.v1;

import java.io.IOException;
import java.io.InputStream;

import com.siteseat.common.misc.IOHelper;

/**
 *
 */
public class CodecHelper {

  /**
   * @param buf
   * @param bodyBytes
   * @return
   * @throws IOException
   * @throws InvalidRequestBodyException
   */
  public static String readText( InputStream ins ) throws IOException {

    int size = IOHelper.readInt( ins );
    if( size == 0 ) {
      return null;
    }

    byte[] tmp = new byte[size];
    IOHelper.readBytes( ins, tmp );

    return new String( tmp, 0, size, IOHelper.CHARSET );
  }

  /**
   * @param ins
   * @return
   * @throws IOException
   */
  public static ErrorMessage readErrorMessage( InputStream ins ) throws IOException {
    ErrorCode code = ErrorCode.get( IOHelper.readInt( ins ) );
    String detail = readText( ins );
    return new ErrorMessage( code, detail );
  }

  public static byte[] getEncodedText( String value ) {

    byte[] bytes = value.getBytes( IOHelper.CHARSET );
    byte[] result = new byte[4 + bytes.length];
    IOHelper.writeInt( result, 0, bytes.length );
    System.arraycopy( bytes, 0, result, 4, bytes.length );
    return result;
  }

}
